package com.itheima.Filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebFilter("/*")
public class LoginFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //1.将请求和响应对象转换为任何HTP协议相关
        HttpServletRequest request= (HttpServletRequest) servletRequest;
        HttpServletResponse response= (HttpServletResponse) servletResponse;
       //2获取会话域对象中数据
        Object username = request.getSession().getAttribute("username");
        //3判断用户名
        //获取相对路径
        String requestURI = request.getRequestURI();
        System.out.println(requestURI);
        //判断并放行的页面
        if(((request.getContextPath())+"/login.jsp").equals(requestURI)||((request.getContextPath())+"/loginStudentServlet").equals(requestURI)){
            filterChain.doFilter(request,response);
            return;
        }
        if(username==null || "".equals(username)){
            //重定向到登录页面
            response.sendRedirect(request.getContextPath()+"/login.jsp");
            return;
        }else{
            filterChain.doFilter(request,response);
        }
    }
}
